package it.aekidna.cleverplatypus.workflow.template
{
	import it.aekidna.cleverplatypus.mediator.CommandEvent;
	import it.aekidna.cleverplatypus.mediator.MediationRegistry;
	import it.aekidna.cleverplatypus.workflow.AbstractWorkflowTask;

	public class DispatchAndListenCommandEventTask extends AbstractWorkflowTask
	{
		public var dispatcherEventName : String;
		public var parameters : Object;
		
		public var listenerEventName : String;
		public var listenerParamNames : Array;
		
		public var faultEventName : String;
		public var faultParamNames : Array;
		
		public var handler : Function;
		
		public function DispatchAndListenCommandEventTask()
		{
			super();
		}

		override public function begin() : void
		{
			MediationRegistry.getInstance().registerMediator( listenerEventName, listenerParamNames, onEvent, this );
			
			if(this.faultEventName)
				MediationRegistry.getInstance().registerMediator( faultEventName, faultParamNames, onFault, this );
				
			CommandEvent.createWithNamedParams( dispatcherEventName, parameters ).dispatch();
		}

		private function onEvent( ... inParams ) : void
		{
			if( handler != null )
			{
				handler.apply( this, inParams );
			}
			
			complete();
		}
		
		
		private function onFault( ... inParams ) : void
		{
			this.fail('Failure event was dispatched');
		}
	}
}